import * as WebSocket from 'ws';
import {sessionManager} from "./session/SessionManager";
import {EventEmitter} from "events";
import {makeId} from "./idMaker";

export class Server extends EventEmitter {
  private wss: WebSocket.Server;

  constructor(private port = 3001) {
    super()
  }

  start() {
    this.wss = new WebSocket.Server({port: this.port});
    this.wss.on("connection", this.onConnected.bind(this))
  }

  private onConnected(ws: WebSocket) {
    //todo auth
    const client = sessionManager.joinClient(ws)

    //todo
    client.user = {name: client.sessionId, uid: makeId()}
    client.id = client.user.uid;
    console.log(client.user)
    this.emit('connected', {target: client})
  }
}